package com.oppo.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.oppo.bean.CarBean;
import com.oppo.bean.OrderBean;
import com.oppo.db.BasicDataOperation;
import com.oppo.tools.MyTools;


@WebServlet("/ToPayAction")
public class ToPayAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String addr = request.getParameter("jia") + request.getParameter("example") +  request.getParameter("adress");
		request.getSession().setAttribute("addr", addr);
		request.getSession().setAttribute("name", request.getParameter("name"));
		request.getSession().setAttribute("phone", request.getParameter("phone_number"));
		request.getSession().getAttribute("car_ids");
		OrderBean ob = new OrderBean();
		ob.setUser_addr(addr);
		String user_id_copy = request.getSession().getAttribute("user_id").toString();
		Long user_id = new Long(user_id_copy);
		ob.setUser_id(user_id);
		ob.setUser_names(request.getParameter("name"));
		String phone_copy = request.getParameter("phone_number");
		Long phone = new Long(phone_copy);
		ob.setUser_phone(phone);
		Object car_id = request.getSession().getAttribute("car_ids");
		CarBean cb = new CarBean();
		@SuppressWarnings("unchecked")
		List<String> list = (List<String>)car_id;
		for (String string : list) {
			Long car_id_cpoy = new Long(string);
			
			cb.setCar_id(car_id_cpoy);//删除购物车记录
			String sql_query = "SELECT * FROM car_t WHERE car_id = " + cb.getCar_id();
			List<CarBean> lst = MyTools.getNewInstance(BasicDataOperation.class).queryData(sql_query, new BeanListHandler<>(CarBean.class));
			ob.setProduct_id(lst.get(0).getProduct_id());
			ob.setProduct_allprice(lst.get(0).getProduct_allprice());
			ob.setProduct_count(lst.get(0).getProduct_count());
			String sql_delete = "DELETE car_t WHERE car_id = " + cb.getCar_id();
			String sql_add = "INSERT INTO order_t(product_id,user_addr,user_names,user_phone,user_id,product_count,product_allprice) VALUES(?,?,?,?,?,?,?)";
			int i_delete = MyTools.getNewInstance(BasicDataOperation.class).updateData(sql_delete);
			int i_Add = MyTools.getNewInstance(BasicDataOperation.class).updateData(sql_add, ob.getProduct_id(),ob.getUser_addr(),ob.getUser_names(),ob.getUser_phone(),ob.getUser_id(),ob.getProduct_count(),ob.getProduct_allprice());
			if(i_delete > 0 && i_Add > 0) {
				System.out.println("加入订单了");
			}
		}
		request.getRequestDispatcher("Payindex.jsp").forward(request, response);
	}

}
